﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DNA.OpenAPI.Atom;
using DNA.Utility;

namespace DNA.Mvc.Services
{
    public class AtomFeedGenerator : CommandContainer
    {
        private AtomFeed feed = null;

        public AtomFeedGenerator()
        {
            feed = new AtomFeed()
            {
                Entries = new List<AtomEntry>()
            };
        }

        public AtomFeedGenerator(IEnumerable<AtomEntriesGeneratorBase> atomGenerators):this()
        {
            this.InnerItems.AddRange(atomGenerators);
        }

        public AtomFeedGenerator SetBaseInfo(string title, string subTitle = "", string id = "", string copyright = "")
        {
            feed.Title = title;
            if (!string.IsNullOrEmpty(subTitle)) feed.SubTitle = subTitle;
            if (!string.IsNullOrEmpty(id)) feed.ID = id;
            if (!string.IsNullOrEmpty(copyright)) feed.CopyRight = copyright;
            return this;
        }

        public AtomFeedGenerator SetLogo(string uri)
        {
            if (!string.IsNullOrEmpty(uri))
                feed.Logo = uri;
            return this;
        }

        public AtomFeedGenerator SetIcon(string uri)
        {
            if (!string.IsNullOrEmpty(uri))
                feed.Icon = uri;
            return this;
        }

        public AtomFeedGenerator SetLastUpdated(DateTime date)
        {
            feed.Updated = date;
            return this;
        }

        public AtomFeedGenerator SetGenerator(string uri, string version = "1.0", string text = "")
        {
            feed.Generator = new AtomGenerator()
            {
                Text = text,
                NavigateUrl = uri,
                Version = version
            };
            return this;
        }

        public AtomFeed GetFeed(object dataValues=null)
        {
            //Invoke(ctx => ctx.Bag = feed);
            Invoke(new CommandContext(dataValues) { Bag=feed });
            return feed;
        }

        public string GetXml(object dataValues = null)
        {
            return XmlSerializerUtility.SerializeToXml(GetFeed(dataValues));
        }
    }
}
